<template>
	<view class="container">
		<view class="calendar-wrapper">
			<uni-calendar :insert="true" :start-date="startDate" :end-date="endDate"
				:disabledDay="disabledDay" :selected="selected" @change="change" @monthSwitch="monthSwitch"/>
		</view>

		<my-popup ref="coursePopup" mode="bottom" :closeable="false">
			<view class="course-popup">
				<view class="title">选择时段</view>
				<view class="category-list">
					<view class="category-item" v-for="(item, i) in timeList" :key="item.tctId" @tap="timeChange(i)"
						:class="{active: item.choosed, disable: item.isChoosed}">{{item.courseTime.startTime}}~{{item.courseTime.endTime}}</view>
				</view>
				<view class="title">
					<text>已选时段</text>
					<text style="padding-left: 20rpx;color:#666666;font-weight: normal;">({{choosedTimeList.length}}/{{lessonNum.lessonNum}})</text>
				</view> 
				<view class="category-list">
					<view class="category-item active choosed-category" style="height: 100rpx;" v-for="(item, index) in choosedTimeList" :key="index">
						<view class="">{{item.chooseDate}}</view>
						<view style="font-size: 28rpx;">{{item.courseTime.startTime}}~{{item.courseTime.endTime}}</view>
						<image src="../../static/images/icon-close.png" class="icon-open" mode="" @tap="delChoosedTime(item)" v-if="!item.orderId"></image>
					</view> 
				</view>
				<view class="bottom-btn-wrapper flex-x-bet-y-center" style="position: relative;padding-bottom: 0;box-shadow: 0rpx 0rpx 0rpx;">
					<view class="cancel-btn btn" @tap="createOrder">暂不选择</view>
					<view class="submit-btn btn" @tap="openTimeModal">确认选择</view>
				</view>
			</view>
		</my-popup>


		<view class="bottom-btn-wrapper flex-y-center">
			<view class="cancel-btn btn" @tap="createOrder">暂不选择</view>
			<view class="submit-btn btn" @tap="openTimeModal">确认选择</view>
		</view>

		<my-modal ref="timeModal" :width="670">
			<view class="time-list">
				<view class="time-modal-tip">*确认后不可更改本次已选时段</view>
				<view class="category-list" style="padding:0;">
					<view class="category-item active choosed-category" style="height: 100rpx;" v-for="(item, index) in currentChoosedTimeList" :key="index">
						<view class="">{{item.chooseDate}}</view>
						<view style="font-size: 28rpx;">{{item.courseTime.startTime}}~{{item.courseTime.endTime}}</view>
					</view>
				</view>
			</view>
		</my-modal> 
	</view>
</template>

<script>
	import { getDisabledDate, getTimeList, createOrder, getOrderInfo} from '@/api/common.js'
	import { mapGetters} from 'vuex'
	export default {
		data() {
			return {
				startDate: '',
				endDate: '',
				selected: [], // 选择过的日期
				disabledDay: [], // 禁用的日期
				timeList: [], // 选择的日期对应的时间段
				choosedTimeList: [],	// 添加的课时
				currentChoosedTimeList: [], // 此次添加课时
				currentDate: {},
				orderId: ''
			};
		},
		onLoad(option) {
			this.orderId = option.orderId || ''
			this.init()
			// 已创建完订单，再次添加节数
			if(this.orderId){
				console.log('已创建完订单，再次添加节数')
				this.getOrderInfo()
			}
		},
		computed:{
			...mapGetters(["teacherId", 'lessonNum', 'courseTag'])
		},
		watch:{
			choosedTimeList(newVal){
				this.currentChoosedTimeList = this.choosedTimeList.filter(item => !item.orderId)
			}
		},
		methods: {
			init() {
				const startDate = this.dayjs().add(1, 'day');
				this.startDate = this.dayjs(startDate).format("YYYY-MM-DD");
				const endDate = this.dayjs().add(180, 'day')
				this.endDate = this.dayjs(endDate).format("YYYY-MM-DD");
				this.getDisabledDate(this.startDate)
			},
			getDisabledDate(date){
				getDisabledDate({teacherId: this.teacherId, date}).then(res => {
					this.disabledDay = res.data
				})
			},
			// 月份切换
			monthSwitch(e){
				const date = e.year + '-' + e.month
				this.getDisabledDate(date)
			},
			// 选择日期
			change(e) {
				const date = e.fulldate;
				this.currentDate = e
				this.timeList = []
				// 查询对应日期的时间段
				getTimeList({teacherId: this.teacherId, date}).then(res => {
					res.data.forEach(item => {
						item.courseTime.startTime = item.courseTime.startTime.substr(0, item.courseTime.startTime.length - 3)
						item.courseTime.endTime = item.courseTime.endTime.substr(0, item.courseTime.endTime.length - 3)
						// 判断已选择的中是否存在当前时间段
						const flag = this.choosedTimeList.find(choosed => choosed.chooseDate == date && choosed.timeId == item.courseTimeId);
						item.choosed = !!flag
					})
					this.timeList = res.data
					this.coursePopupOpen()
				})
			},
			coursePopupOpen() {
				this.$refs.coursePopup.open()
			},
			timeChange(index) {
				const timeObj = this.timeList[index]
				// 此次已被选择 || 已被其他用户选择
				if(timeObj.choosed || timeObj.isChoosed){
					 return
				}
				// 超过最大可选择节数
				if(this.choosedTimeList.length == this.lessonNum.lessonNum){
					return this.toast('可选节数已满');
				}
				timeObj.choosed = true
				// 打点已选择
				let selected = this.selected.find(item => item.date == this.currentDate.fulldate)
				if(!selected){
					this.selected.push({
							date: this.currentDate.fulldate
					});
				}
				// 添加到已选择的时间段里
				this.choosedTimeList.push({
					teacherId: this.teacherId,
					timeId: timeObj.courseTimeId,
					chooseDate: this.currentDate.fulldate,
					weekNum: this.currentDate.lunar.nWeek,
					courseTime: {
						startTime: timeObj.courseTime.startTime,
						endTime: timeObj.courseTime.endTime
					}
				})
			},
			delChoosedTime(timeObj){
				let index = -1;
				for(var i = 0; i < this.choosedTimeList.length; i++){
					// 找到日期与时间段相同的索引
					if(this.choosedTimeList[i].chooseDate == timeObj.chooseDate && this.choosedTimeList[i].timeId == timeObj.timeId){
						index = i;
					}
				}
				// 删除已选择
				if(index > -1){
					// 时间段的choosed置否
					const delTime = this.choosedTimeList[index]
					this.timeList.forEach(item => {
						if(item.courseTimeId == delTime.timeId && this.currentDate.fulldate == delTime.chooseDate){
							item.choosed = false
						}
					})
					this.choosedTimeList.splice(index, 1)
					// 判断是否显示日期打点
					const flag = this.choosedTimeList.find(item => item.chooseDate == timeObj.chooseDate);
					// 已选择的没有当前日期的，删除点标记
					if(!flag){
						let selectedIndex = this.selected.findIndex(item => item.chooseDate == timeObj.chooseDate)
						this.selected.splice(selectedIndex, 1)
					}
				}
			},
			openTimeModal() {
				// 非二次选课 && 未选择课时
				if(!this.currentChoosedTimeList.length && !this.orderId){
					return this.toast('请选择课时')
				}
				// 有新增
				if(this.currentChoosedTimeList.length){
					this.$refs.timeModal.open({
						title: '是否确认选择？',
						zIndex: 99999,
						success: () => {
							let param = {
								orderId: this.orderId || undefined,
								teacherId: this.teacherId,
								lessonNum: this.lessonNum.lessonNum,
								courseTagId: this.courseTag.courseTagId,
								userCourseTimeList: this.choosedTimeList
							}
							this.submit(param)
						},
						cancel: () => {
							
						}
					})
				}
				// 二次选择，无新增
				else{
					this.submitSuccessHandle()
				}
			},
			submit(param){
				createOrder(param).then(res => {
					this.orderId = res.data
					// 此次选择的置空
					this.choosedTimeList = []
					this.submitSuccessHandle()
				})
			},
			submitSuccessHandle(){
				const pages = getCurrentPages();
				const prePage = pages[pages.length - 2]; // 上一页面
				const fullPage = prePage.$page.fullPath
				// 确认订单页过来，二次选课
				if(fullPage.indexOf('/pages/order/order_confirm') != -1){
					uni.navigateBack()
				}
				// 订单列表页或详情页进入，二次选课
				else if(fullPage.indexOf('/pages/order/index') != -1 || fullPage.indexOf('/pages/order/order_detail') != -1){
					uni.$emit('refresh');
					uni.navigateBack()
				}
				else{
					uni.redirectTo({
						url:'/pages/order/order_confirm?orderId=' + this.orderId
					})
				}
			},
			createOrder(){
				let param = {
					orderId: this.orderId || undefined,
					teacherId: this.teacherId,
					lessonNum: this.lessonNum.lessonNum,
					courseTagId: this.courseTag.courseTagId
				}
				this.submit(param)
			},
			getOrderInfo(){
				getOrderInfo(this.orderId).then(res => {
					this.choosedTimeList = []
					// 已选择过的课时
					res.data.courseTime.forEach(item => {
						item.courseTime.startTime = item.courseTime.startTime.substr(0, item.courseTime.startTime.length - 3)
						item.courseTime.endTime = item.courseTime.endTime.substr(0, item.courseTime.endTime.length - 3) 
					})
					this.choosedTimeList.push(...res.data.courseTime)
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		padding-top: 1rpx;
		background-color: #F3F3F3;
	}

	.calendar-wrapper {
		margin: 30rpx;
	}

	.btn {
		flex: 1;
	}

	.btn:first-of-type {
		margin-right: 30rpx;
	}

	.course-popup {
		width: 100%;
		background: #FFFFFF;

		.title {
			padding: 40rpx 30rpx 0;
			font-size: 30rpx;
			font-weight: bold;
			color: #333333;
		}

		.right-btn {
			width: 312rpx;
			height: 100%;
			background: $theme-color;
			font-size: 34rpx;
			color: #FFFFFF;
		}
	}

	.time-list {
		padding: 30rpx 0;
		
		.time-modal-tip{
			text-align: center;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: $theme-color;
		}
	}
	
	.category-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
		padding: 0 30rpx;
		width: 100%;
		min-height: 300rpx;
		max-height: 600rpx;
		overflow-y: auto;
	
		.category-item {
			padding: 15rpx 0;
			height: 70rpx;
			flex: 0 0 calc((100% - 60rpx) / 3);
			margin: 30rpx 30rpx 0 0;
			background: #F8F9FB;
			border: 1rpx solid #F8F9FB;
			border-radius: 16rpx;
			font-size: 30rpx;
			font-weight: 500;
			color: #333333;
			text-align: center;
		}
	
		.category-item:nth-of-type(3n) {
			margin-right: 0;
		}
	
		.disable {
			background: #F8F9FB;
			color: #BEBEBE;
		}
	
		.active {
			background: #FFFAF7;
			border: 1rpx solid $theme-color;
			color: $theme-color;
		}
	
		.choosed-category {
			position: relative;
	
			.icon-open {
				position: absolute;
				top: -15rpx;
				right: -15rpx;
				width: 36rpx;
				height: 36rpx;
			}
		}
	}
</style>